<!--
 * 严肃声明：
 * 开源版本请务必保留此注释头信息，若删除我方将保留所有法律责任追究！
 * 本系统已申请软件著作权，受国家版权局知识产权以及国家计算机软件著作权保护！
 * 可正常分享和学习源码，不得用于违法犯罪活动，违者必究！
 * Copyright (c) 2020 陈尼克 all rights reserved.
 * 版权所有，侵权必究！
 *
-->

<template>
  <div class="address-edit-box">
    <s-header name="发布需求/商品"></s-header>
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="state.form.title"
          name="标题"
          label="标题"
          placeholder="标题"
          :rules="[{ required: true, message: '请填写标题' }]"
        />
        <van-field name="radio" label="类型">
          <template #input>
            <van-radio-group
              v-model="state.form.type"
              :rules="[{ required: true, message: '请选择一个选项' }]"
              direction="horizontal"
            >
              <van-radio name="0">需求</van-radio>
              <van-radio name="1">商品</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field
          v-model="state.form.city"
          name="地点"
          label="地点"
          placeholder="地点"
          :rules="[{ required: true, message: '请填写地点' }]"
        />
        <van-field name="radio" label="价格类型">
          <template #input>
            <van-radio-group v-model="state.ptype" direction="horizontal">
              <van-radio name="0">单价</van-radio>
              <van-radio name="1">区间</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field
          v-model="state.form.salary_down"
          v-if="state.ptype === '1'"
          type="number"
          label="最低价"
          placeholder="最低价"
          :rules="[{ required: true, message: '请填写最低价' }]"
        />
        <van-field
          v-model="state.form.salary_up"
          v-if="state.ptype === '1'"
          type="number"
          label="最高价"
          placeholder="最高价"
          :rules="[{ required: true, message: '请填写最高价' }]"
        />
        <van-field
          v-model="state.form.salary_down"
          v-if="state.ptype === '0'"
          type="number"
          label="单价"
          placeholder="单价"
          :rules="[{ required: true, message: '请填写单价' }]"
        />
        <van-field
          v-model="state.form.quantity"
          type="number"
          label="数量"
          placeholder="数量"
          :rules="[{ required: true, message: '请填写数量' }]"
        />

        <van-field
          v-model="state.form.company_name"
          label="公司名"
          disabled
          placeholder="公司名"
          :rules="[{ required: true, message: '请填写公司名' }]"
        />

        <van-field
          v-model="state.fieldValue"
          is-link
          readonly
          label="分类"
          placeholder="请选择分类"
          @click="showCate = true"
        />
        <van-popup v-model:show="showCate" round position="bottom">
          <van-cascader
            :props="props"
            v-model="state.cascaderValue"
            title="请选择分类"
            :options="state.categoryData"
            @close="showCate = false"
            @finish="onFinish"
            :field-names="fieldNames"
            :rules="[{ required: true, message: '请选择分类' }]"
          />
        </van-popup>

        <van-field name="uploader" label="封面图上传">
          <template #input>
            <van-uploader
              v-model="state.form.cover_img2"
              :after-read="afterRead"
            />
          </template>
        </van-field>

        <van-field
          v-model="state.form.requirement"
          rows="4"
          autosize
          label="需求概述"
          type="textarea"
          placeholder="请输入需求概述"
          :rules="[{ required: true, message: '请填写需求概述' }]"
        />

        <p>详情：</p>

        <editor
          v-model="state.htmlContent"
          @editor="receiveEditor"
          placeholder="请输入详情信息"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { reactive, onMounted, ref } from "vue";
import { showToast, showNotify } from "vant";
import sHeader from "@/components/SimpleHeader.vue";
import Editor from "@/components/Editor.vue";
import { getCategory, uploadFile, getHR, update } from "@/service/good";
import {
  addAddress,
  EditAddress,
  DeleteAddress,
  getAddressDetail,
} from "@/service/address";
import { tdist } from "@/common/js/utils";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
const showCate = ref(false);
const state = reactive({
  areaList: {
    province_list: {},
    city_list: {},
    county_list: {},
  },
  searchResult: [],
  type: "add",
  ptype: "0",
  addressId: "",
  addressInfo: {},
  form: {
    title: "",
    type: "0",
    city: "",
    salary_down: "",
    salary_up: "",
    cover_img: "",
    parent_id: "",
    category_id: "",
  },
  categoryData: [],
  fieldValue: "",
  cascaderValue: "",
  user: "",
  htmlContent: "",
});
const fieldNames = {
  text: "name",
  value: "id",
  children: "children",
};
const props = {
  multiple: false, //是否多选
  emitPath: true, //通过最后一级的id回显
};

onMounted(async () => {
  const { item } = route.query;
  state.form = JSON.parse(item);

  state.form.cover_img2 = [
    {
      url: state.form.cover_img,
    },
  ];

  state.cascaderValue = state.form.category_id;
  state.htmlContent = state.form.details;

  const { data } = await getCategory();
  state.categoryData = data;
  data.map((p) => {
    if (p.id === state.form.parent_id) {
      state.fieldValue += p.name;

      p.children.map((c) => {
        if (c.id === state.form.category_id) {
          state.fieldValue += "/" + c.name;
        }
      });
    }
  });

  const user = localStorage.getItem("user");

  state.user = JSON.parse(user);

  hr();
});

const onSave = async (content) => {
  const params = {
    userName: content.name,
    userPhone: content.tel,
    provinceName: content.province,
    cityName: content.city,
    regionName: content.county,
    detailAddress: content.addressDetail,
    defaultFlag: content.isDefault ? 1 : 0,
  };
  if (state.type == "edit") {
    params["addressId"] = state.addressId;
  }
  (await state.type) == "add" ? addAddress(params) : EditAddress(params);

  showToast({
    message: "保存成功",
    className: "particulars-detail-popup",
  });
  setTimeout(() => {
    router.back();
  }, 1000);
};

const onDelete = async () => {
  await DeleteAddress(state.addressId);
  showToast("删除成功");
  setTimeout(() => {
    router.back();
  }, 1000);
};

const onFinish = ({ selectedOptions }) => {
  showCate.value = false;
  state.fieldValue = selectedOptions.map((option) => option.name).join("/");

  const ids = selectedOptions.map((option) => option.id);

  if (ids && ids.length > 0) {
    state.form.parent_id = ids[0] || "";
    state.form.category_id = ids[1] || "";
  }
};

const afterRead = async (file) => {
  // 此时可以自行将文件上传至服务器

  const formdata = new FormData();
  formdata.append("file_0", file.file);

  const res = await uploadFile(formdata);

  if (res && res.length > 0) {
    state.form.cover_img = res[0].url;
  }
};

const hr = async () => {
  try {
    const res = await getHR(state.user.id);
    state.form.hr_id = state.user.id;

    if (res.state && res.state === 1) {
      state.form.company_name = res.name;
      state.form.company_id = res.id;
    } else {
      showToast({
        message: "未完成企业认证不能发布需求/商品",
        className: "particulars-detail-popup",
      });
      setTimeout(() => {
        router.back();
      }, 1500);
    }
  } catch (error) {
    showToast({
      message: "未完成企业认证不能发布需求/商品",
      className: "particulars-detail-popup",
    });
    setTimeout(() => {
      router.back();
    }, 1500);
  }
};

const receiveEditor = async (val) => {
  console.log(val);
};

const onSubmit = async () => {
  if (state.form.cover_img === "") {
    showToast({
      message: "请上传封面图",
      className: "particulars-detail-popup",
    });
    return;
  }
  if (!state.form.parent_id || !state.form.category_id) {
    showToast({
      message: "请选择分类信息",
      className: "particulars-detail-popup",
    });
    return;
  }
  const params = { ...state.form };
  params.details = state.htmlContent;
  const res = await update(params);
  state.loading = false;
  showToast({
    message: res.message,
    className: "particulars-detail-popup",
  });
  router.back();
};
</script>

<style lang="less">
@import "../common/style/mixin";
.edit {
  .van-field__body {
    textarea {
      height: 26px !important;
    }
  }
}
.address-edit-box {
  .van-address-edit {
    .van-button--danger {
      background: @primary;
      border-color: @primary;
    }
    .van-switch--on {
      background: @primary;
    }
  }
}
</style>
